/*
 * @title: 动态加载路由和导航守卫配置
 * @author: andy.ten@tom.com & xukaixing@hotmail.com
 * @Date: 2022-03-19 19:22:17
 * @LastEditors: andy.ten@tom.com
 * @LastEditTime: 2022-06-06 13:14:34
 * @version: 1.0.6
 * @copyright: copyright (c) 2022 andyten
 *  node: you can not copy and/or use and/or modify this program free,
 *  please reserve the segment above.Please mail me if you have any question.
 */

import router from './routers';
import store from '@/store';
import Settings from '@/settings';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';// progress bar style
import { getToken } from '@/utils/ht.auth';
import { getGrantedMenus } from '@/api/ht.login';
import { buildRouters } from '@/utils/ht.permission';
import { MyError, handleKeepAlive } from '@/utils';
import Hawthorn from 'hawthorn-ui/lib/hawthorn-ui.umd.min.js';
NProgress.configure({ showSpinner: false }); // showSpinner：隐藏右上角进度圆环

// 免登录白名单 - 无须重定向，直接进入
const whiteList = ['/login'];

// 免权限白名单
// const whiteAuth = ['/login', '/home', '/redirect', '/404', '/401'];

// 阻止跳转
const noJump = (next) => {
  next(false);
  NProgress.done();
};

// 登录判断
const hasToken = () => {
  if (process.env.MOCK_DATA === 'true')
    return true;
  else
    return getToken();
};

router.beforeEach(async(to, from, next) => {
  if (to.meta.title)
    document.title = Settings.websiteTitle + ' - ' + to.meta.title;

  NProgress.start();
  if (hasToken())
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else {
      if (store.getters.userInfo.grantreload === '1' || store.getters.navMenus.length === 0) {
        try {
          await loadNavMenus(to, next, 1);
        } catch (error) {
          await store.dispatch('user/resetToken');
          next(`/login?redirect=${to.path}`);
          // location.reload();
        }
        NProgress.done();
      } else if (store.getters.permsRoutes.length === 0) {
        await loadNavMenus(to, next, 0);
        handleKeepAlive(to).then(() => {
          next();
        }, noJump(next));
      } else {
        if (to.path !== '/dashboard')
          await store.dispatch('perms/setBreadcrumbRoutes', to.matched);

        handleKeepAlive(to).then(() => {
          next();
        }, noJump(next));
      }
    }
  else
  if (whiteList.includes(to.path))
    next();
  else {
    next(`/login?redirect=${to.path}`);
    NProgress.done();
  }
});

/**
 * @todo: 动态加载已授权的功能菜单
 * @author: andy.ten@tom.com & xukaixing@hotmail.com
 * @Date: 2022-03-27 09:23:45
 * @param {*} to
 * @param {*} next
 */
export const loadNavMenus = async(to, next, type) => {
  const params = { rootName: '0', menuLayout: '1', userAccount: store.getters.loginAccount };
  try {
    let sidebarRouters = [];
    if (type === 1) {
      const { datas } = await getGrantedMenus(params);
      sidebarRouters = buildRouters(JSON.parse(datas));

      // 设置 store navMenus
      store.dispatch('user/setNavMenus', JSON.stringify(datas));
      // store.dispatch('SetSidebarRouters', sidebarRoutes);
    } else
      sidebarRouters = buildRouters(JSON.parse(store.getters.navMenus));

    store.dispatch('perms/setSidebarRoutes', sidebarRouters).then(() => {
      // router.addRoutes(store.state.perms.routes); // 动态添加可访问路由表
      // 如果 addRoutes 并未完成，路由守卫会一层一层的执行执行，直到 addRoutes 完成，找到对应的路由
      next({ ...to, replace: true });
    });
  } catch (error) {
    console.log(error);
    Hawthorn.Notify.alert(error, 'error');
    return Promise.reject(new MyError(error));
  }
};

router.afterEach(() => {
  NProgress.done(); // finish progress bar
});
